package com.bolt.support.spring.mvc.resolver;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.SortHandlerMethodArgumentResolver;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;

public class CustomSortResolver extends SortHandlerMethodArgumentResolver {

    @Override
    public Sort resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
                                NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) {
        JsonNode body = ResolverUtil.getJsonBody(webRequest);
        if (!body.isNull() && body.has("sort")) {
            JsonNode treeNode = body.get("sort");
            if (treeNode.isArray()) {
                ArrayNode arrayNode = (ArrayNode) treeNode;
                List<Sort.Order> orders = new ArrayList<>();
                for (JsonNode jsonNode : arrayNode) {
                    Sort.Order order = new Sort.Order(Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
                            jsonNode.get("property").textValue());
                    orders.add(order);
                }
                return Sort.by(orders);
            }
            return Sort.unsorted();
        }
        return super.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
    }

}